﻿using RpcHelper;
using SqlExecHelper;
using Wedonek.RpcStore.Service.DAL;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Service.Collect
{
        internal class DictateNodeCollect : BasicCollect<DictateNodeDAL>, IDictateNodeCollect
        {
                private DictateNodeRelationDAL _Relation = null;

                private DictateNodeRelationDAL _RelationDAL
                {
                        get
                        {
                                if (this._Relation == null)
                                {
                                        this._Relation = new DictateNodeRelationDAL ();
                                }
                                return this._Relation;
                        }
                }

                public long Add (DictateNewNode add)
                {
                        long[] ids = this._RelationDAL.GetParents (add.ParentId);
                        ids = ids.Add (add.ParentId);
                        using (ITransaction tran = base.GetCollect<ITransaction> ())
                        {
                                long id = base.BasicDAL.Add (add);
                                this._RelationDAL.Add (id, ids);
                                tran.Commit ();
                                return id;
                        }

                }
                public void Drop (DictateNode obj)
                {
                        long[] subId = this._RelationDAL.GetSubs (obj.Id);
                        subId = subId.Add (obj.Id);
                        using (ITransaction tran = base.GetCollect<ITransaction> ())
                        {
                                base.BasicDAL.Drop (subId);
                                this._RelationDAL.Drop (subId);
                                tran.Commit ();
                        }
                }
                public DictateNode[] Gets ()
                {
                        return base.BasicDAL.Gets ();
                }
                public DictateNode Get (long id)
                {
                        DictateNode node = base.BasicDAL.Get (id);
                        if (node == null)
                        {
                                throw new ErrorException ("rpc.dictate.node.not.find");
                        }
                        return node;
                }
                public DictateNode[] Gets (long parentId)
                {
                        long[] ids = this._RelationDAL.GetSubs (parentId);
                        return base.BasicDAL.Gets (ids);
                }
                public void Set (DictateNode node, string name)
                {
                        if (node.DictateName == name)
                        {
                                return;
                        }
                        base.BasicDAL.Set (node.Id, name);
                }
        }
}
